import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_hx/model/result.dart';
import 'package:get/get.dart';

import '../widgets/view_state_helper.dart';

@optionalTypeArgs
mixin ListViewGetControllerMixin<T> on GetxController{
  final EasyRefreshController refreshController=EasyRefreshController();

  bool _initData=false;

  final viewStatus=ViewState.loading.obs;

  final dataSource=RxList<T>([]);

  int _page=1;

  @protected
  final int pageSize=20;

  void _appendPage(){
    queryMap["pageNum"]=_page;
    queryMap["pageSize"]=pageSize;
  }


  Future onRefresh() async{
    if(!_initData && viewStatus.value==ViewState.error){
      viewStatus.value=ViewState.loading;
    }
    final old=int.parse(_page.toString());
    _page=1;
    _appendPage();
    final res=await loadData();
    res.ifSuccess((data) {
      if(data.isNotEmpty){
        dataSource.value=data;
      }
      if(!_initData){
        viewStatus.value=data.isNotEmpty?ViewState.success:ViewState.empty;
        _initData=true;
        return;
      }
      final isNoMore=data.length<pageSize;
      refreshController.finishRefresh(success:true,noMore: false);
      if(isNoMore){
        refreshController.finishLoad(success: true,noMore: true);
      }else{
        refreshController.resetLoadState();
      }
    });
    res.ifFailure((e){
      if(!_initData){
        viewStatus.value=ViewState.error;
      }
    });
  }

  Future onLoad()async{
    _page=_page+1;
    _appendPage();
    final res=await loadData();
    res.ifSuccess((data){
      if(data.isNotEmpty){
        // ignore: invalid_use_of_protected_member
        final news=dataSource.value;
        news.addAll(data);
        dataSource.value=news;
        refreshController.finishLoad(success: true,noMore: data.length<pageSize);
      }else{
        refreshController.finishLoad(success: true,noMore: true);
      }
    });
    res.ifFailure((e) => _page=_page-1);
  }

  var queryMap=<String,dynamic>{};

  @protected
  Future<Result<List<T>>>  loadData();

  @override
  @mustCallSuper
  void onClose() {
       debugPrint("onClose");
      refreshController.dispose();
  }


}